# author: Han Zhang
library(maptools)
library(ggplot2)
library(plyr)
library(RColorBrewer)

library(dict)
library(stringi)
library(jsonlite)


d = read.csv('../../output/protest_events.csv', encoding = "utf-8", stringsAsFactors = F,sep = "\t")
d$date = sapply(strsplit(d$event_id, "_"), "[", 2)

d$date <- as.Date(d$date)
d$month = substr(d$date, 0, 7)
d$city_code <- paste (substr(d$event_id, 1,4), "00",sep = "")

### city-level counts
agg_city = as.data.frame.table (table( d$city_code))
colnames(agg_city) <- c("city_code",  "event_count")
agg_city$city_code = as.integer(as.character(agg_city$city_code))

## read shapefiles
str.crs <- "+proj=longlat +ellps=clrk66"
china_map <- readShapePoly("prefecture-shapefile/CN-shi-A.shp",proj4string=CRS(str.crs))


x <- china_map@data
x$id = seq(0:(nrow(x)-1))
x$chn_name <- stri_encode(x$CityNameC, "gb2312", "utf-8")

## merge shapefiles and counts at the prefecture level 
xs <- merge(x, agg_city, by.x = "SHI", by.y = "city_code",all.x = T)
xs$id = xs$id - 1

china_map1 <- fortify(china_map)             
china_map_data <- join(china_map1, xs, type = "full")       


pdf("protest_region_count_prefecture_log_scale.pdf", width = 6, height = 4)

p <- ggplot(china_map_data)
p <- p +
  theme(               
    panel.grid = element_blank(),
    panel.background = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_blank(),
    legend.position = c(0.95, 0.45)
  ) +
  guides(fill = guide_legend(title = "Logged\ncounts of\nCASM-\nChina\nevents\n(2010-17)"))

p1 <- p + geom_polygon(data = china_map_data, aes(x = long, y = lat,group = group,fill= log (event_count)),colour="grey60")+
  geom_path(data = china_map_data, aes(x = long, 
                                 y = lat, 
                                 group = group), 
            color = "white", size = 0.1) +
  scale_fill_distiller(palette="Blues",  direction=1)
p1
dev.off()

# convert the PDF to png, with DPI = 300, following the solution with the below link
# https://askubuntu.com/questions/50170/how-to-convert-pdf-to-image

system("convert -density 300 protest_region_count_prefecture_log_scale.pdf protest_region_count_prefecture_log_scale.png")
